/**
 * 名称：SmartHomeNode 获取温湿度
 * 时间：2021-03-11
 * 功能：上报温湿度
 * 上报：
 *     温度 TEMP/:T1/:17
 *     湿度 HUM/:T1/:65
 */
#include <SimpleDHT.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

/**--------------------------- 配置 WiFi 信息 ------------------------------*/
#ifndef STASSID
#define STASSID "OpenWrt"           // WiFi 名称
#define STAPSK  "12345678"          // WiFi 密码
#endif
/**--------------------------- 配置 服务器 信息 ------------------------------*/
const char SERVIER_IP[] = "192.168.1.1";    // 远程服务器IP
const int SERVIER_PORT = 50005;             // 远程服务器端口
const int LocalPort = 8888;                 // 设备自己UDP服务端口
const String DeviceName = "T1";             // 设备名称
/*------------------------------- 控制引脚 ---------------------------------*/
const int pinDHT11 = 4;                 // 温湿度传感器引脚
const int pinLED = 2;                   // LED 控制引脚（低电平亮）
/**--------------------------------------------------------------------------*/

/* 控制码 */
const String TEMPSEND = "TEMP/:" + DeviceName + "/:";
const String HUMSEND = "HUM/:" + DeviceName + "/:";
String TEMPDATA = "";
String HUMDATA = "";

SimpleDHT11 dht11(pinDHT11);

// read without samples.
byte SensorTemp = 0;
byte SensorHum = 0;

// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE + 1]; //buffer to hold incoming packet,

WiFiUDP Udp;

/**
 * 系统灯亮一下
 */
void alarmLED() {
    digitalWrite(pinLED, LOW);
    delay(333);
    digitalWrite(pinLED, HIGH);
}

/**
 * 发送数据到指定服务器（UDP方式）
 * [sendHumidity description]
 */
void sendHumidity() {
  if (SERVIER_IP != "" && SERVIER_PORT != 0) {
    Udp.beginPacket(SERVIER_IP, SERVIER_PORT);
    Udp.write((TEMPSEND+TEMPDATA).c_str());
    Udp.endPacket();
    delay(random(999));
    Udp.beginPacket(SERVIER_IP, SERVIER_PORT);
    Udp.write((HUMSEND+HUMDATA).c_str());
    Udp.endPacket();
  }
}

/**
 * 读取温湿度
 * [readHumidity description]
 */
void readHumidity() {
  // start working...
  Serial.println("=================================");
  Serial.println("Sample DHT11...");
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&SensorTemp, &SensorHum, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err=");
    Serial.print(SimpleDHTErrCode(err));
    Serial.print(",");
    Serial.println(SimpleDHTErrDuration(err));
    delay(1000 + random(999));
    readHumidity();
  } else {
    TEMPDATA = (String)SensorTemp;
    HUMDATA = (String)SensorHum;
    Serial.println("temperature:");
    Serial.println(TEMPDATA);
    Serial.println("humidity:");
    Serial.println(HUMDATA);
  }
}

/**
 * 系统初始化
 * [setup description]
 */
void setup() {
  Serial.begin(115200);
  pinMode(pinLED, OUTPUT);          // 初始化led
  digitalWrite(pinLED, pinLED);       // 配置LED为低电平
  WiFi.mode(WIFI_STA);
  WiFi.begin(STASSID, STAPSK);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    alarmLED();
    delay(666);
  }
  Serial.println("***");
  Serial.print("Connected! IP address: ");
  Serial.println(WiFi.localIP().toString().c_str());
  Serial.printf("UDP server on port %d\n", LocalPort);
  Udp.begin(LocalPort);
}

/**
 * 主方法
 */
void loop() {
  // 循环发3次，每次间隔5秒
  for (int i = 0; i < 3; ++i)
  {
    readHumidity();
    sendHumidity();
    alarmLED();
    delay(5000);
  }
  delay(60000);
}